import { availableEvaluationDate, evaluationSummary } from '@/services/api/api-assess-week-quality';
import {
  ActionType,
  ProColumns,
  ProFormCascader,
  ProFormRadio,
  ProTable,
  QueryFilter,
} from '@ant-design/pro-components';
import { Radio, RadioChangeEvent } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
interface TableQualityProps {}

const TableQuality: React.FC<TableQualityProps> = ({}) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const [mediaLevel, setMediaLevel] = useState('市属媒体');
  const [dateType, setDateType] = useState('月份');
  const [siteChannel, setSiteChannel] = useState('微信公众号');

  //   const [selectMonth, setSelectMonth] = useState<string>('');
  const [selectWeek, setSelectWeek] = useState<string>('');

  const [monthOptions, setMonthOptions] = useState<string[]>([]);
  const [weekOptions, setWeekOptions] = useState<string[]>([]);

  const [dateOptions, setDateOptions] = useState<any[]>([]);

  useEffect(() => {
    const fetchOptions = async () => {
      const request = await availableEvaluationDate();

      if (request.code == 0) {
        setMonthOptions(request.data.months);
        setWeekOptions(request.data.weeks);

        // setSelectMonth(request.data.months[request.data.months.length - 1]);
        // setSelectWeek(request.data.weeks[request.data.weeks.length - 1]);
        setSelectWeek(request.data.months[request.data.months.length - 1]);

        setDateOptions(
          request.data.months.map((month) => {
            return {
              value: month,
              label: month,
              children: [
                {
                  value: month,
                  label: month,
                },
                ...request.data.weeks
                  .filter((week) => week.startsWith(month))
                  .map((week) => {
                    return {
                      value: week,
                      label: week,
                    };
                  }),
              ],
            };
          }),
        );
      }
    };

    fetchOptions();
  }, []);

  const columns: ProColumns<AssessWeekQualityData.EvaluationList>[] = [
    {
      title: '排名',
      dataIndex: 'index',
      valueType: 'indexBorder',
      width: '50px',
    },
    {
      title: '参评账号',
      dataIndex: 'sourceSite',
      ellipsis: true,
      width: '120px',
      align: 'center',
      hidden: mediaLevel != '市属媒体',
    },
    {
      title: '参评账号',
      dataIndex: 'douyinSourceSite',
      ellipsis: true,
      width: '120px',
      align: 'center',
      hidden: mediaLevel != '区县媒体' || siteChannel == '总排名',
    },
    {
      title: '媒体单位',
      dataIndex: 'mediaName',
      ellipsis: true,
      width: '120px',
      align: 'center',
    },
    {
      title: '账号得分',
      dataIndex: 'totalScore',
      ellipsis: true,
      width: '120px',
      align: 'center',
      render: (_, row, index, action) => {
        if (mediaLevel == '市属媒体') {
          return <>{row.totalScore}</>;
        } else {
          if (siteChannel == '微信公众号') {
            return <>{row.weixinScore}</>;
          } else if (siteChannel == '微博') {
            return <>{row.weiboScore}</>;
          } else if (siteChannel == '抖音') {
            return <>{row.douyinScore}</>;
          } else if (siteChannel == '微信视频号') {
            return <>{row.weixinVideoScore}</>;
          } else if (siteChannel == '今日头条') {
            return <>{row.toutiaoScore}</>;
          } else {
            return <>{row.totalScore}</>;
          }
        }
      },
    },
    // {
    //   title: '操作',
    //   valueType: 'option',
    //   width: '120px',
    //   fixed: 'right',
    //   render: (_, row, index, action) => [
    //     <a key="a_reset_bind_wechat" onClick={async () => {}}>
    //       详情
    //     </a>,
    //   ],
    // },
  ];

  return (
    <>
      {monthOptions.length > 0 &&
      weekOptions.length > 0 &&
      dateOptions.length > 0 &&
      selectWeek != '' ? (
        <>
          <QueryFilter
            initialValues={{
              mediaLevel: '市属媒体',
              //   dateType: '月份',
              //   month: monthOptions[monthOptions.length - 1],
              //   week: weekOptions[weekOptions.length - 1],
              week: [
                [
                  dateOptions[dateOptions.length - 1].value,
                  dateOptions[dateOptions.length - 1].value,
                ],
              ],
            }}
            layout="vertical"
            submitter={false}
            style={{
              padding: 0,
            }}
          >
            <ProFormRadio.Group
              name="mediaLevel"
              label="媒体等级"
              radioType="button"
              options={[
                {
                  label: '市属媒体',
                  value: '市属媒体',
                },
                {
                  label: '区县媒体',
                  value: '区县媒体',
                },
              ]}
              fieldProps={{
                buttonStyle: 'solid',
                onChange(e) {
                  setMediaLevel(e.target.value);
                  if (e.target.value == '市属媒体') {
                    setSiteChannel('微信公众号');
                  } else if (e.target.value == '区县媒体') {
                    setSiteChannel('总排名');
                  }
                  actionRef.current?.reloadAndRest();
                },
              }}
            />
            <ProFormCascader
              name="week"
              label="选择"
              style={{ marginLeft: '16px' }}
              width="md"
              fieldProps={{
                labelInValue: true,
                options: dateOptions,
                displayRender: (labels: string[], selectedOptions?: any[]) => {
                  return labels.map((label, i) => {
                    if (selectedOptions) {
                      const option = selectedOptions[i];
                      if (i === labels.length - 1) {
                        return <span key={option.value}>{label}</span>;
                      }
                      return <></>;
                    } else {
                      return '';
                    }
                  });
                },
                onChange(value, selectedOptions) {
                  setSelectWeek(value[value.length - 1]);
                  actionRef.current?.reloadAndRest();
                },
              }}
            />

            {/* <ProFormRadio.Group
              name="dateType"
              label="时间类型"
              radioType="button"
              options={[
                {
                  label: '月份',
                  value: '月份',
                },
                {
                  label: '周数',
                  value: '周数',
                },
              ]}
              fieldProps={{
                buttonStyle: 'solid',
                onChange(e) {
                  setDateType(e.target.value);
                  actionRef.current?.reloadAndRest();
                },
              }}
            /> */}
            {/* <ProFormSelect
              name="month"
              label="选择月份"
              style={{ marginLeft: '16px' }}
              hidden={dateType == '周数'}
              width="md"
              fieldProps={{
                labelInValue: true,
                onChange(value, option) {
                  setSelectMonth(value.value);
                  actionRef.current?.reloadAndRest();
                },
              }}
              options={monthOptions.map((item) => {
                return { label: item, value: item };
              })}
            /> */}
            {/* <ProFormSelect
              name="week"
              label="选择周数"
              style={{ marginLeft: '16px' }}
              hidden={dateType == '月份'}
              width="md"
              fieldProps={{
                labelInValue: true,
                onChange(value) {
                  setSelectWeek(value.value);
                  actionRef.current?.reloadAndRest();
                },
              }}
              options={weekOptions.map((item) => {
                return { label: item, value: item };
              })}
            /> */}
          </QueryFilter>

          <ProTable
            headerTitle={
              <div style={{ display: 'flex', flexDirection: 'column' }}>
                <span
                  style={{
                    marginRight: '10px',
                    fontSize: 18,
                    fontWeight: 'bold',
                    marginBottom: '20px',
                  }}
                >
                  {mediaLevel}传播质效
                  {/* <span style={{ fontSize: '16px', color: '#979797' }}>
                    {dateType == '月份'
                      ? `${dayjs(selectMonth)
                          .subtract(1, 'month')
                          .format('YYYY-MM')}-21 ~ ${selectMonth}-21 `
                      : selectWeek}
                  </span> */}
                  <span style={{ fontSize: '16px', color: '#979797' }}>
                    {selectWeek.includes('~')
                      ? selectWeek
                      : `${dayjs(selectWeek)
                          .subtract(1, 'month')
                          .format('YYYY-MM')}-21 ~ ${selectWeek}-21 `}
                  </span>
                </span>
                <Radio.Group
                  value={siteChannel}
                  buttonStyle="solid"
                  size="middle"
                  onChange={(e: RadioChangeEvent) => {
                    const value = e.target.value;
                    setSiteChannel(e.target.value);
                    actionRef.current?.reloadAndRest();
                  }}
                >
                  {mediaLevel === '区县媒体' && <Radio.Button value="总排名">总排名</Radio.Button>}
                  <Radio.Button value="微信公众号">微信公众号</Radio.Button>
                  <Radio.Button value="微博">微博</Radio.Button>
                  <Radio.Button value="抖音">抖音</Radio.Button>
                  <Radio.Button value="微信视频号">微信视频号</Radio.Button>
                  <Radio.Button value="今日头条">今日头条</Radio.Button>
                </Radio.Group>
              </div>
            }
            style={{
              marginTop: '16px',
            }}
            cardProps={{
              bodyStyle: {
                padding: 0,
              },
            }}
            bordered={false}
            columns={columns}
            actionRef={actionRef}
            rowKey="areaId"
            search={false}
            request={async (params = {}) => {
              //   let yearMonth = '';
              //   if (dateType == '月份') {
              //     yearMonth = selectMonth;
              //   } else if (dateType == '周数') {
              //     yearMonth = selectWeek;
              //   }

              const response = await evaluationSummary({
                mediaLevel,
                yearMonth: selectWeek,
                siteChannel,
              });

              let evaluationList: any[] = [];

              if (siteChannel == '微信公众号') {
                evaluationList = response.data?.evaluationList?.sort((n1, n2) => {
                  return n2.weixinScore - n1.weixinScore;
                });
              } else if (siteChannel == '微博') {
                evaluationList = response.data?.evaluationList?.sort((n1, n2) => {
                  return n2.weiboScore - n1.weiboScore;
                });
              } else if (siteChannel == '抖音') {
                evaluationList = response.data?.evaluationList?.sort((n1, n2) => {
                  return n2.douyinScore - n1.douyinScore;
                });
              } else if (siteChannel == '微信视频号') {
                evaluationList = response.data?.evaluationList?.sort((n1, n2) => {
                  return n2.weixinVideoScore - n1.weixinVideoScore;
                });
              } else if (siteChannel == '今日头条') {
                evaluationList = response.data?.evaluationList?.sort((n1, n2) => {
                  return n2.toutiaoScore - n1.toutiaoScore;
                });
              } else {
                evaluationList = response.data?.evaluationList;
              }

              return Promise.resolve({
                data: evaluationList,
                total: evaluationList?.length,
                success: response.code === 0,
              });
            }}
            sticky
            // scroll={{
            //   x: '1300px',
            // }}
            pagination={false}
            onRow={(record) => {
              return {
                onClick: () => {},
              };
            }}
          />
        </>
      ) : (
        <></>
      )}
    </>
  );
};
export default TableQuality;
